package comboingRedient

import (
	"context"
	"time"

	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/comboingredient"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/predicate"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/svc"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/utils/dberrorhandler"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/types/pancakebot"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
    "github.com/zeromicro/go-zero/core/logx"
)

type GetComboIngredientListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetComboIngredientListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetComboIngredientListLogic {
	return &GetComboIngredientListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetComboIngredientListLogic) GetComboIngredientList(in *pancakebot.ComboIngredientListReq) (*pancakebot.ComboIngredientListResp, error) {
	var predicates []predicate.ComboIngredient
	if in.CreatedAt != nil {
		predicates = append(predicates, comboingredient.CreatedAtGTE(time.UnixMilli(*in.CreatedAt)))
	}
	if in.UpdatedAt != nil {
		predicates = append(predicates, comboingredient.UpdatedAtGTE(time.UnixMilli(*in.UpdatedAt)))
	}
	if in.ComboId != nil {
		predicates = append(predicates, comboingredient.ComboIDEQ(*in.ComboId))
	}
	if in.IngredientId != nil {
		predicates = append(predicates, comboingredient.IngredientIDEQ(*in.IngredientId))
	}
	if in.IsRequired != nil {
		predicates = append(predicates, comboingredient.IsRequiredEQ(*in.IsRequired))
	}
	if in.Quantity != nil {
		predicates = append(predicates, comboingredient.QuantityEQ(int(*in.Quantity)))
	}
	if in.Price != nil {
		predicates = append(predicates, comboingredient.PriceEQ(*in.Price))
	}
	result, err := l.svcCtx.DB.ComboIngredient.Query().Where(predicates...).Page(l.ctx, in.Page, in.PageSize)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, in)
	}

	resp := &pancakebot.ComboIngredientListResp{}
	resp.Total = result.PageDetails.Total

	for _, v := range result.List {
		resp.Data = append(resp.Data, &pancakebot.ComboIngredientInfo{
			Id:          &v.ID,
			CreatedAt:   pointy.GetPointer(v.CreatedAt.UnixMilli()),
			UpdatedAt:   pointy.GetPointer(v.UpdatedAt.UnixMilli()),
			ComboId:	&v.ComboID,
			IngredientId:	&v.IngredientID,
			IsRequired:	&v.IsRequired,
			Quantity:	pointy.GetPointer(int64(v.Quantity)),
			Price:	&v.Price,
		})
	}

	return resp, nil
}
